package com.yzr.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

/**
 * @description 字节流读写
 * @author: yx-0173
 * @date: 2021-05-24 14:58
 **/
public class ByteStreamUtil {
    private static final Logger log = Logger.getLogger("com.yzr.common.util.ByteStreamUtil");
    private static int len;
    private static final byte[] BYTES = new byte[2048];
    private static boolean result = false;
    private static String stringResult = null;

    /**
     * 读取流
     *
     * @param file 文件对象
     * @return 字符串
     */
    public static String fileIn(File file) {
        try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file))) {
            if (!file.exists()) {
                throw new IOException("此文件不存在");
            }
            while ((len = stream.read(BYTES)) != -1) {
                stringResult = new String(BYTES, 0, len, "GBK");
            }
        } catch (Exception e) {
            log.info("错误...");
        }
        return stringResult;
    }

    /**
     * 写入流
     *
     * @param file    文件对象
     * @param content 内容
     * @return 是否成功
     */
    public static boolean fileOut(File file, String content) {
        try (BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(file))) {
            if (!file.exists()) {
                throw new IOException("此文件不存在");
            }
            if (content.length() > 0) {
                stream.write(content.getBytes());
                result = true;
            }
        } catch (Exception e) {
            log.info("错误...");
        }
        return result;
    }

    /**
     * 写入流
     *
     * @param in  读取流对象
     * @param out 写入流对象
     */
    public static void fileCopy(InputStream in, OutputStream out) {
        try (BufferedOutputStream outputStream = new BufferedOutputStream(out);
             BufferedInputStream inputStream = new BufferedInputStream(in)) {
            while ((len = inputStream.read(BYTES)) != -1) {
                outputStream.write(BYTES, 0, len);
            }
        } catch (Exception e) {
            log.info("错误...");
        }
    }

}
